<template>
	<view class="container">
<!--        <view class="condition-select">-->
<!--            <text v-for="(item,index) in tabList" :key="index" @click="tabChange(item)"-->
<!--                  class="item" :class="{'selected': currentTab == item.value}">-->
<!--                {{item.name}}-->
<!--            </text>-->
<!--        </view>-->

        <view class="center">
            <view class="item">
                <view class="top-content">
                    <view class="number-content">
                        <text>{{data_ratio}}</text>
                        <text>%</text>
                    </view>
                    <view class="number-content">
                      <text>{{data_kg}}</text>
                      <text>kg</text>
                    </view>
                    <u-icon v-if="is_online == 1" color="#3380ff" size="35" name="minus"></u-icon>
                    <u-icon v-if="is_online == 0" color="#FF5833" size="35" name="minus"></u-icon>
                </view>
                <text class="bottom-text">剩余水量</text>
            </view>
            <view class="item">
                <view class="top-content">
                    <view class="number-content">
                        <text>{{stock_num}}</text>
                        <text>桶</text>
                    </view>
<!--                    <u-icon color="#f53634" size="35" name="arrow-upward"></u-icon>-->
                </view>
                <text class="bottom-text">现库存水量</text>
            </view>
        </view>

        <view class="charts-container">
            <text class="title">用水量统计图</text>
            <canvas v-show="!charImg" canvas-id="canvasLineA" id="canvasLineA" class="charts" @touchstart="touchCharts"></canvas>
            <image v-if="charImg" :src="charImg" class="charts" style="display: block"></image>
        </view>

        <view class="bottom-container">
<!--            <view class="item">-->
<!--                <text class="key">已使用</text>-->
<!--                <text class="value" style="font-weight: bold;">256天</text>-->
<!--            </view>-->
            <view class="item">
                <text class="key">设备添加日期</text>
                <text class="value">{{created_at}}</text>
            </view>
        </view>

        <view style="display: flex;flex-direction: row;width: 100%;">
          <view class="button-container" @click="resetPeel" style="background-color: #e06513">
              重置重量
          </view>
          <view class="button-container" @click="openModal">
              满桶重量
          </view>
        </view>

        <u-modal v-model="modalShow" title="请输入满桶重量(kg)" :show-cancel-button="true" :z-index="99999999" @confirm="modalBtnConfirm">
            <view class="slot-content">
                <view style="padding: 20rpx">
                    <u-input v-model="inputValue" :border="true"></u-input>
                </view>
            </view>
        </u-modal>

    </view>
</template>

<script>
    import uCharts from './u-charts.js';
    import {getDeviceLastData} from "../../api";
    let canvasLineA = null
    export default {
        data() {
            return {
                currentTab: '',
                tabList: [{name: '日',value: 1},{name: '周',value: 2},{name: '月',value: 3},{name: '年',value: 4}],
                cWidth: '',
                cHeight: '',
                pixelRatio: 1,
                canvasId: 'canvasLineA',
                chartData: {
                    categories: ['周一', '周二', '周三', '周四', '周五', '周六','周七'],
                    series: [{
                        name: '桶数',
                        data: [70, 40, 65, 100, 44, 68,55,11]
                    }]
                },
                modalShow: false,
                inputValue: '',
                charImg: '',
                lastNum:0,
              interval:'',
              deviceNum:'',
              is_online:0,
              data_ratio:0,
              data_kg:0,
              stock_num:0,
              created_at:"",
              changeStock:0,
            }
        },
        watch: {
            modalShow(val) {
                if (!val) {
                    const that = this
                    setTimeout(() => {
                        that.charImg = ''
                    },500);
                }
            }
        },
        onShow(){
          this.interval = setInterval(this.getDeviceLastData,1000);
        },
        onLoad(options) {
            this.deviceNum=options.device_num
            // this.getOrderDetail();
            this.currentTab = this.tabList[0].value
            this.initCharts()
        },
        methods: {
          async getDeviceList(){
            let params = {
              user_token: wx.getStorageSync("userToken")
            }

            const res=await this.$api.myDeviceList(params,this.$baseUrl);
            if(res.data.level == "success"){
              // uni.showToast({
              //   icon: 'none',
              //   title: res.data.message,
              //   duration: 1500
              // })
              this.device_list  = res.data.data.device_list;
              this.device_count = res.data.data.device_count;
            }else {
              uni.showToast({
                icon: 'none',
                title: res.data.message,
                duration: 1500
              })
            }
          },

            initCharts() {
                this.cWidth = uni.upx2px(710);
                this.cHeight = uni.upx2px(400);
                const _self = this;
                const canvasId = this.canvasId
                const chartData = this.chartData
                canvasLineA = new uCharts({
                    context: wx.createCanvasContext(canvasId, _self),
                    type: 'line',
                    fontSize: 11,
                    legend: {
                        show: true
                    },
                    dataLabel: false,
                    dataPointShape: true,
                    background: '#FFFFFF',
                    pixelRatio: _self.pixelRatio,
                    categories: chartData.categories,
                    series: chartData.series,
                    animation: true,
                    xAxis: {
                        type: 'grid',
                        gridColor: '#CCCCCC',
                        gridType: 'dash',
                        dashLength: 8
                    },
                    yAxis: {
                        gridType: 'dash',
                        gridColor: '#CCCCCC',
                        dashLength: 8,
                        splitNumber: 5
                    },
                    width: _self.cWidth * _self.pixelRatio,
                    height: _self.cHeight * _self.pixelRatio,
                    extra: {
                        line: {
                            type: 'straight'
                        }
                    }
                });
            },

            tabChange(item) {
                this.currentTab = item.value
            },

            touchCharts(e) {
                canvasLineA.showToolTip(e, {
                    format: function(item, category) {
                        return category + ' ' + item.name + ':' + item.data
                    }
                });
            },

            openModal() {
                this.modalShow = true
                this.handleCanvasToImg()
            },

            async modalBtnConfirm() {
              let params = {
                user_token: wx.getStorageSync("userToken"),
                device_num:this.deviceNum,
                max_num:this.inputValue
              }

              const res=await this.$api.setDeviceMaxNum(params,this.$baseUrl);
              if(res.data.level == "success"){
                uni.showToast({
                  icon: 'none',
                  title: res.data.message,
                  duration: 1500
                })

              }else {
                uni.showToast({
                  icon: 'none',
                  title: res.data.message,
                  duration: 1500
                })
              }
            },

            //canvas的层级太高，弹窗时只能将canvas转成图片展示出来
            handleCanvasToImg() {
                const that = this
                wx.canvasToTempFilePath({
                    x: 0,
                    y: 0,
                    width: this.cWidth,
                    height: this.cHeight,
                    canvasId: this.canvasId,
                    success: function(res) {
                        that.charImg = res.tempFilePath;
                    }
                });
            },

          async getDeviceLastData(){
            let params = {
              user_token: wx.getStorageSync("userToken"),
              device_num:this.deviceNum
            }
            /* this.loadingStatus = 'loading'; */
            let res=await this.$api.getDeviceLastData(params,this.$baseUrl);
            if(res.data.level=='success'){
                this.data_kg = res.data.data.data_kg;
                this.data_ratio = res.data.data.data_ratio;
                this.is_online = res.data.data.is_online;
                this.stock_num = res.data.data.stock_num;
                this.created_at = res.data.data.created_at;

                if(this.data_ratio > 90){
                  this.changeStock=0;
                }

                if(this.data_ratio < 2 && this.changeStock==0){
                  var _this = this;
                  clearInterval(_this.interval);
                  wx.showModal({
                    title: '提示',
                    content: `水量即将用完，现在要换水吗？`,
                    showCancel: true,
                    confirmText: '确定',
                    success(res) {
                      if (res.confirm) {
                        _this.changeStockNumRequest();
                      } else if (res.cancel) {
                        uni.showToast({
                          title: "已取消操作",
                          icon: 'none',
                          duration: 1500
                        })
                      }

                    }
                  })
                }
            } else{
              uni.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 1500
              })
            }
          },
          async changeStockNumRequest(){
            let params = {
              user_token: wx.getStorageSync("userToken"),
            }
            let res=await this.$api.changeStockNum(params,this.$baseUrl);
            if(res.data.level=='success'){
              this.changeStock = 1;
              uni.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 1500
              })
            } else{
              if(res.data.data == "no_stock"){
                uni.showToast({
                  title: res.data.message,
                  icon: 'none',
                  duration: 1500
                })

                setTimeout(()=>{
                  wx.navigateTo({
                    url:"/pages/deliverWater/index"
                  });
                },2500)
              }else {
                uni.showToast({
                  title: res.data.message,
                  icon: 'none',
                  duration: 1500
                })
              }

            }
            this.interval = setInterval(this.getDeviceLastData,1000);
          },
          resetPeel(){
            wx.showModal({
              title: '重置重量',
              content: `是否确认进行重量去皮？`,
              showCancel: true,
              confirmText: '确定',
              success(res) {
                if (res.confirm) {
                  this.resetRequest()
                } else if (res.cancel) {
                  uni.showToast({
                    title: "已取消操作",
                    icon: 'none',
                    duration: 1500
                  })
                }

              }
            })
          },
          async resetRequest(){
            /* this.loadingStatus = 'loading'; */
            let params = {
              user_token: wx.getStorageSync("userToken"),
              device_num:this.deviceNum
            }
            let res=await this.$api.resetPeel(params,this.$baseUrl);
            if(res.data.level=='success'){
              uni.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 1500
              })
            } else{
              uni.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 1500
              })
            }
          },

        }
    };
</script>

<style lang="scss" scoped>

    .container {
        color: #333333;
        font-size: 28rpx;
        .condition-select {
            padding: 20rpx 30rpx;
            display: flex;
            justify-content: space-between;
            .item {
                width: 145rpx;
                padding: 15rpx 0;
                display: flex;
                justify-content: center;
                align-items: center;
                border-radius: 50rpx;
                box-shadow: 0px 0px 8px 0px rgba(119, 163, 149, 0.2);
                color: grey;
            }
            .selected {
                color: #ffffff;
                background-color: #3b87ff;
            }
        }
        .center {
            padding: 20rpx 30rpx;
            display: flex;
            justify-content: space-between;
            .item {
                width: 330rpx;
                box-sizing: border-box;
                padding: 25rpx;
                display: flex;
                flex-direction: column;
                box-shadow: 0px 0px 8px 0px rgba(119, 163, 149, 0.2);
                .top-content {
                    display: flex;
                    justify-content: space-between;
                    .number-content {
                        vertical-align: baseline;
                        text:first-child {
                            font-size: 36rpx;
                            color: #333333;
                            font-weight: bold;
                        }
                        text:last-child {
                            color: grey;
                            margin-left: 15rpx;
                        }
                    }
                }
                .bottom-text {
                    padding: 20rpx 0 0;
                    color: grey;
                    font-size: 28rpx;
                }
            }
        }

        .charts-container {
            margin-top: 20rpx;
            .title {
                font-size: 30rpx;
                margin-left: 30rpx;
            }
            .charts {
                width: 710upx;
                height: 400upx;
                margin: 30rpx auto;
            }
        }

        .bottom-container {
            width: 710rpx;
            background-color: #fafafc;
            margin: auto;
            display: flex;
            flex-direction: column;
            box-sizing: border-box;
            padding: 20rpx;
            justify-content: space-between;
            .item {
                display: flex;
                width: 100%;
                margin-top: 8rpx;
                justify-content: space-between;
                .key {
                    color: grey;
                }
                .value {
                }
            }
        }

        .button-container {
            width: 320rpx;
            height: 80rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #3b87ff;
            color: #ffffff;
            border-radius: 80rpx;
            margin-top: 50rpx;
            margin-left: auto;
            margin-right: auto;
        }


    }

</style>

<style>
    .top-content .u-icon__icon {
        font-weight: bold !important;
    }
</style>
